package com.doform.android.xianggucheng.activity.library;

import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.activity.BaseTitleActivity;
import com.doform.android.xianggucheng.bean.ArticleQueryBean;
import com.doform.android.xianggucheng.bean.GuidBean;
import com.doform.android.xianggucheng.bean.InLibraryDetailBean2;
import com.doform.android.xianggucheng.bean.request_bean.ReqAddInlibraryDetail;
import com.doform.android.xianggucheng.bean.request_bean.ReqDeleteInLibraryDetailBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqListInLibraryBean2;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.DialogTransformer;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.doform.android.xianggucheng.widget.ITextWatcher;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者 Y_MS
 * Created by ${APEN} on 2017-07-18.
 * GitHub：https://github.com/cxydxpx
 */

public class LibraryDetailOrActivity extends BaseTitleActivity {

    @BindView(R.id.tv_article_name)
    TextView tv_article_name;

    @BindView(R.id.tv_unit)
    TextView tv_unit;

    @BindView(R.id.et_number)
    EditText et_number;

    @BindView(R.id.et_price)
    EditText et_price;

    @BindView(R.id.et_remark)
    EditText et_remark;

    @BindView(R.id.tv_sum_price)
    TextView tv_sum_price;

    @BindView(R.id.tv_sum_price2)
    TextView tv_all_price;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    private String sumPrice;
    private String mId;
    private String mGuid;

    private String goodId;
    private String goodName;
    private String goodUnit;
    private String number;
    private String price;
    private String remart;
    private ArticleQueryBean mGoodsBean;
    private String misId;
    private double mAllPrice = 0;
    private String mLibraryId;
    private CommonAdapter<InLibraryDetailBean2.ListBean> mCommonAdapter;
    private List<InLibraryDetailBean2.ListBean> mDatas = new ArrayList<>();

    @Override
    protected int layoutResId() {
        return R.layout.activity_new_add_library_detail;
    }

    @Override
    protected void init() {
        super.init();
        String id = getIntent().getStringExtra(Constans.EXTRA_ADD_LIBRARY_ID);
        String guid = getIntent().getStringExtra(Constans.EXTRA_ADD_LIBRARY_GUID);
        String mLibraryId = getIntent().getStringExtra(Constans.EXTRA_ADD_LIBRARY_LIBRARY_ID);
        this.mLibraryId = mLibraryId;
        this.mGuid = guid;
        this.mId = id;
    }


    @Override
    protected void initData() {
        super.initData();
        getDataListForService(mId);
    }

    /**
     * 获取采购单明细
     *
     * @param id
     */
    private void getDataListForService(String id) {
        HttpManager
                .instance()
                .getInLibraryListDetail(new ReqListInLibraryBean2(id))
                .subscribe(new ErrorHandleSubscriber<InLibraryDetailBean2>() {
                               @Override
                               public void onNext(@NonNull InLibraryDetailBean2 listBean) {
                                   mDatas.clear();
                                   mDatas.addAll(listBean.getList());
                                   mAllPrice = listBean.getTotal();
                                   notifyUi(mAllPrice);
                                   mCommonAdapter.notifyDataSetChanged();
                               }
                           }
                );
    }

    @Override
    protected void initView() {
        super.initView();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        et_price.addTextChangedListener(new ITextWatcher() {

            @Override
            public void afterTextChanged(Editable s) {

                String s1 = et_number.getText().toString().trim();

                if (TextUtils.isEmpty(s1)) {
                    s1 = "0";
                }
                int a = Integer.parseInt(s1);

                String s2 = et_price.getText().toString().trim();

                if (TextUtils.isEmpty(s2)) {
                    s2 = "0";
                }

                Double b = Double.parseDouble(s2);
                double v = a * b;
                sumPrice = String.valueOf(v);

                tv_sum_price.setText("￥" + sumPrice);

            }
        });

        et_number.addTextChangedListener(new ITextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                String s1 = et_price.getText().toString().trim();

                if (TextUtils.isEmpty(s1)) {
                    s1 = "0";
                }
                int a = Integer.parseInt(s1);

                String s2 = et_number.getText().toString().trim();

                if (TextUtils.isEmpty(s2)) {
                    s2 = "0";
                }

                Double b = Double.parseDouble(s2);
                double v = a * b;

                sumPrice = String.valueOf(v);

                tv_sum_price.setText("￥" + sumPrice);
            }
        });


    }


    @Override
    protected void initListener() {
        super.initListener();

        mCommonAdapter = new CommonAdapter<InLibraryDetailBean2.ListBean>(this, R.layout.activity_new_add_library_detail_item, mDatas) {
            @Override
            protected void convert(ViewHolder holder, final InLibraryDetailBean2.ListBean dataBean, int position) {
                TextView tv_name = holder.getView(R.id.tv_name);
                TextView tv_price = holder.getView(R.id.tv_price);
                TextView tv_number = holder.getView(R.id.tv_number);
                TextView tv_sum_price = holder.getView(R.id.tv_sum_price);
                RelativeLayout rl_delete = holder.getView(R.id.rl_delete);

                tv_name.setText(dataBean.getName());
                tv_number.setText(dataBean.getBuynum());
                tv_price.setText(dataBean.getBuyprice());
                tv_sum_price.setText(Double.valueOf(dataBean.getBuynum()) * Double.valueOf(dataBean.getBuyprice()) + "");

                rl_delete.setOnClickListener(new View.OnClickListener() {
                                                 @Override
                                                 public void onClick(View v) {
                                                     deleteItem(dataBean);
                                                 }
                                             }
                );
            }
        };

        mRecyclerView.setAdapter(mCommonAdapter);

    }

    /**
     * 删除明细条目
     *
     * @param bean
     */
    private void deleteItem(final InLibraryDetailBean2.ListBean bean) {
        HttpManager
                .instance()
                .deleteInLibraryDetail2(new ReqDeleteInLibraryDetailBean(mId, bean.getGuid()))
                .subscribe(new ErrorHandleSubscriber<Integer>() {
                               @Override
                               public void onNext(@NonNull Integer num) {
                                   getDataListForService(mId);
                               }
                           }
                )
        ;
    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("添加采购明细");
    }

    private void beforeSubmit() {

        if (mDatas.size() == 0) {
            TsUtils.showToast("请采购商品");
            return;
        }

        if (TextUtils.isEmpty(mId)) {
            TsUtils.showToast("订单失效，请重新制作");
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("applyid", mId);
        intent.putExtra("sumPrice", sumPrice);
        intent.putExtra(Constans.EXTRA_ADD_LIBRARY_BOOLEAN, true);
        setResult(Constans.REQUEST_NEW_LIBRARY, intent);
        finish();

    }

    private void beforeAdd() {

        number = et_number.getText().toString().trim();
        price = et_price.getText().toString().trim();
        remart = et_remark.getText().toString().trim();


        if (TextUtils.isEmpty(goodId)) {
            TsUtils.showToast("请选择商品");
            return;
        } else if (TextUtils.isEmpty(number)) {
            TsUtils.showToast("请输入采购数量");
            return;
        } else if (TextUtils.isEmpty(price)) {
            TsUtils.showToast("请输入采购价格");
            return;
        } else if (TextUtils.isEmpty(remart)) {
            remart = "";
        }

        postDataToService(mId,mGuid, misId, goodId, mLibraryId, number, price);

    }


    private void postDataToService(String id, String guid,String misId, String goodId, String mLibraryId, String number, String price) {
        HttpManager
                .instance()
                .addLibraryDetail(new ReqAddInlibraryDetail(id,guid, misId, goodId, mLibraryId, number, price))
                .subscribeOn(Schedulers.io())
                .compose(new DialogTransformer<GuidBean>(mProgressBar))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<GuidBean>() {
                               @Override
                               public void onNext(@NonNull GuidBean bean) {
                                   getDataListForService(mId);
                               }
                           }
                );
    }

    private void notifyUi(double mAllPrice) {
        tv_article_name.setText("");
        tv_sum_price.setText("");
        tv_unit.setText("");
        et_number.setText("");
        et_price.setText("");
        et_remark.setText("");
        goodId = null;
        number = null;
        price = null;
        remart = null;

        tv_all_price.setText("￥" + mAllPrice);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            switch (requestCode) {
                case Constans.REQYEST_ADD_LIBRARY_ADD_GOODS:
                    ArticleQueryBean bean = (ArticleQueryBean) data.getSerializableExtra(Constans.EXTRA_ADD_LIBRARY_SEARCH_GOODS);
                    this.mGoodsBean = bean;
                    updateUi(bean);
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);

    }


    private void updateUi(ArticleQueryBean bean) {
        goodId = bean.getId();
        misId = bean.getM2sid();
        goodName = bean.getName();
        goodUnit = bean.getUnit();
        tv_article_name.setText(goodName);
        tv_unit.setText(goodUnit);
    }

    @OnClick({R.id.tv_article_name, R.id.btn_add, R.id.btn_submit})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.tv_article_name:
                Intent intent = new Intent(this, ListArticlaActivity2.class);
                startActivityForResult(intent, Constans.REQYEST_ADD_LIBRARY_ADD_GOODS);
                break;
            case R.id.btn_add:
                beforeAdd();
                break;
            case R.id.btn_submit:
                beforeSubmit();
                break;
            default:
                break;
        }
    }

}
